import express from "express";
import webpack from "webpack";
import webpackConfig from "../build/config";
import session from "express-session";
import compression from "compression";
import bodyParser from "body-parser";
import Loadable from 'react-loadable';
import path from "path";
const { JSDOM } = require("jsdom");
import stats from '../dist/react-loadable.json';

const publicPath = '/dist/';
const app = express();
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
    url: "http://localhost"
});

global.window = dom.window;
global.document = window.document;
global.navigator = window.navigator;

var exdate = new Date();
exdate.setTime(exdate.getTime() + 10000000);

Loadable.preloadAll();
app.use(session({
    cookie: { maxAge: 10000},
    name: 'test',
    secret: 'lvhe',
    rolling: false,
    saveUninitialized: true,
    resave: true
}));

if(process.env.NODE_ENV == "server") {
    const compiler = webpack(webpackConfig());
    app.use(compression());
    const options = {
        publicPath: '/',
        quiet: true,
        noInfo: true,
        hot: true,
        stats: {color: true}
    };

    app.use(require("webpack-dev-middleware")(compiler, options));
    app.use(require("webpack-hot-middleware")(compiler));
}

app.use(bodyParser.text());
app.use(bodyParser.json());
console.log("请求开始...");
// console.log(path.resolve(__dirname, "../dist"));
app.use('/dist', express.static(path.resolve(__dirname, "../dist")));
// app.use("/dist");
app.use(function(err, req, res, next) {
    console.log("错误信息:", err);
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: app.get("env") === "server" ? err : {}
    });
});
app.use((req, res, next) => {
    req.__stats = stats;
    next();
});
// 客户端读取的初始化用户数据
app.use("/state/(:key).js", (req, res) => {
    res.type("text/javascript");
    const content = `
    window.__INITIAL_STATE__ = ${JSON.stringify(req.session.state)}`;
    res.send(content);
});

// app.get('/', (req, res) => {
//     console.log(req.sessionID);
//     if(req.session.views){
//         req.session.views++;
//         res.end(JSON.stringify(req.session));
//     } else {
//         req.session.views = 1;
//         res.end(JSON.stringify(req.session));
//     }
// });
// console.log(require("../dist/ssr").default);

app.use(require("../dist/ssr").default);
app.disable("x-powered-by");
const server = app.listen('7111', () => {
    const {port} = server.address();
    console.log(`Listened at http://localhost:${port}`);
});